<template>
	<view class="container" v-if="config.config">
		<form @submit="formSubmit">
			<view class="verification">
				<view class="list cf" v-if="national_list.length > 0">
					<picker @change="national_change" :range="national_list_show">
						<view class="picker">
							<view class="fl c333"><lang keywords="国家/地区"></lang></view>
							<view class="fr national_show c333">
								{{ national_check.show }}
								<text class="iconfont icon-xiala ml10"></text>
							</view>
						</view>
					</picker>
				</view>
				<view class="clearfix list">
					<input type="number" name="phone" :placeholder="placeholder_phone" class="fl phoneInput" @input="inputPhone" maxlength="11" />
					<view class="fr codeBox">
						<view class="box receive" :style="'background:' + config.config.mobile_head_color" v-if="judge > 0" @click.stop="loop">
							<lang keywords="获得验证码"></lang>
						</view>
						<view class="box send_out" v-else>
							<lang keywords="已发送"></lang>
							(
							<text class="second">{{ time }}</text>
							s)
						</view>
					</view>
				</view>
				<view class="list"><input type="number" name="code" :placeholder="placeholder_code" maxlength="4" /></view>
			</view>
			<view class="button">
				<button formType="submit" :style="'background:' + config.config.mobile_head_color"><lang keywords="提交"></lang></button>
			</view>
		</form>
		<!-- #ifdef MP-WEIXIN -->
		<view class="wxapp-button" v-if="!config.config.international_phone">
			<button size="mini" :plain="true" open-type="getPhoneNumber" @getphonenumber="getUserWxPhone">
				<image src="../../static/images/weixin_small.png"></image>
				<lang keywords="使用微信绑定手机号"></lang>
			</button>
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-ALIPAY -->
		<view class="wxapp-button alipay" v-if="!config.config.international_phone">
			<button size="mini" :plain="true" open-type="getPhoneNumber" @getphonenumber="getAlipayPhone">
				<text class="iconfont icon-zhifubao"></text>
				<lang keywords="使用支付宝绑定手机号"></lang>
			</button>
		</view>
		<!-- #endif -->
		
		<view class="user-tip">
			<lang keywords="登录代表您已同意"></lang>
			<view class="block-in" @tap="goUrl(config.register_agreement_url)">
				<lang :style="'color:' + config.config.mobile_head_color" keywords="用户协议"></lang>，
			</view>
			<view class="block-in" @tap="goUrl(config.privacy_policy_url)">
				<lang :style="'color:' + config.config.mobile_head_color" keywords="隐私政策"></lang>，
			</view>
			<lang keywords="并授权使用您的账号信息（如呢城、头像、收货地址）以使您进行统一管理"></lang>
		</view>

		<userinfo v-if="user_options.toLogin" :options="user_options" @getUserscope="getUserInfo" @toLogin="getUserInfo"></userinfo>
	</view>
</template>

<script>
import common from '../../utils/common.js';
var app = getApp();
var newphone = '';
var pageBackNum = 1;
var _this;

export default {
	data() {
		return {
			userInfo: {},
			config: {},
			judge: '1',
			time: 60,
			national_list: [],
			national_list_show: [],
			national_check: {},
			placeholder_phone: '请输入手机号码',
			placeholder_code: '请输入验证码',
			user_options: {},
			third_id: ''
		};
	},

	onLoad(options) {
		// #ifdef H5
		common.webToMiniapp('/pages/my/newnumber', options)
		// #endif
		
		_this = this;
		newphone = '';
		if (options.third_id) {
			console.log('111111111111绑定手机号', options);
			_this.third_id = options.third_id
			_this.third_from = options.third_from
		} else {
			if (!app.globalData.is_login) {
				common.getTabBar(function(tabBar){
					console.log('1111111', tabBar)
					uni.reLaunch({
						url: tabBar.list[0].pagePath
					})
				})
			} else {
				this.userInfo = app.globalData.userInfo;
			}
		}

		if (options.source && options.source == 'edit') {
			pageBackNum = 2;
			wx.setNavigationBarTitle({
				title: common.changeTxt('绑定新手机号')
			});
		} else {
			wx.setNavigationBarTitle({
				title: common.changeTxt('绑定手机号')
			});
		}

		_this.placeholder_phone = common.changeTxt(_this.placeholder_phone);
		_this.placeholder_code = common.changeTxt(_this.placeholder_code);

		console.log(options);
		console.log(pageBackNum);
		common.setMainColor(_this, function(config) {
			_this.config = config;

			if (config.config.international_phone) {
				app.getNationalPhone(function(national_list) {
					var national_list_show = [];

					for (var i in national_list) {
						national_list_show.push(national_list[i].show);
					}

					var national_check = national_list[0];

					_this.national_list = national_list;
					_this.national_list_show = national_list_show;
					_this.national_check = national_check;
				});
			}
		});
		console.log('111111111111', app.globalData.is_login);
		
	},
	onShow () {
		// #ifdef H5
		common.hideWxShare()
		// #endif
	},
	methods: {
		goUrl (url) {
			common.parseUrl(url)
		},
		getUserInfo(e) {
			if (e && e.userInfo) {
				this.userInfo = e.userInfo;
			}
		},
		getAlipayPhone(e) {
			console.log('获取支付宝手机号111333', e);
			let param = {}
			let url = 'Login&a=alipayapp_deciphering'
			if (_this.third_id) {
				param.third_id = _this.third_id
				param.third_from = _this.third_from
				param.phone_from = 'alipayapp'
				url = 'Login&a=third_id_login'
			}
			my.getPhoneNumber({
				success: res => {
					let encryptedData = res.response;
					param.response = encryptedData
					console.log('成功', res);
					common.post(url, param, function(data) {
						console.log('成功111', JSON.stringify(data));
						if (_this.third_id) {
							uni.$emit('loginSuccess', data)
							common.navigateBack(pageBackNum)
						} else if (data && data.phone) {
							app.globalData.userInfo.phone = data.phone;
							common.navigateBack(pageBackNum);
						}
					});
				},
				fail: res => {
					console.log('失败', res);
					wx.showToast({
						title: common.changeTxt('获取手机号失败'),
						icon: 'none'
					});
				} 
			});
								
		},
		inputPhone: function(e) {
			newphone = e.detail.value;
		},
		getUserWxPhone: function(e) {
			console.log(e);

			if (e.detail.errMsg == 'getPhoneNumber:ok') {
				var object = {
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv,
					type: 'change_user_phone'
				};
				if(_this.third_id){
					object.phone_from = 'wxapp'
					object.third_id = _this.third_id
					object.third_from = _this.third_from
					common.post('Login&a=third_id_login', object, function(data) {
						uni.$emit('loginSuccess', data) 
						common.navigateBack(pageBackNum)
					});
				} else {
					app.getUserWxPhone(object, function(result) {
						console.log(result);
						app.globalData.userInfo = result;
						common.navigateBack(pageBackNum);
					});
				}
			} else {
				wx.showModal({
					title: common.changeTxt('获取手机号失败'),
					content: e.detail.errMsg.replace('getPhoneNumber:fail Error:', '').replace('getPhoneNumber:', ''),
					showCancel: false
				});
			}
		},
		formSubmit: function(e) {
			console.log(e.detail);

			if (_this.config.config.international_phone) {
				if (newphone.length == 0) {
					wx.showModal({
						title: common.changeTxt('提示'),
						content: common.changeTxt('请输入手机号码'),
						showCancel: false
					});
					return false;
				}
			} else {
				if (newphone.length != 11) {
					wx.showModal({
						title: common.changeTxt('提示'),
						content: common.changeTxt('请输入11位的手机号码'),
						showCancel: false
					});
					return false;
				}
			}

			if (e.detail.value.code.length != 4) {
				wx.showModal({
					title: common.changeTxt('提示'),
					content: common.changeTxt('请输入4位的验证码'),
					showCancel: false
				});
				return false;
			}

			var postData = {
				phone: e.detail.value.phone,
				type: 2,
				code: e.detail.value.code,
				client: 3
			};

			if (app.merchantOwn && !_this.userInfo.phone) {
				postData.other_id = _this.userInfo.mer_id;
				postData.bind_id = _this.userInfo.id;
			}

			if (_this.national_check && _this.national_check.code) {
				postData.phone_country_type = _this.national_check.code;
			}

			_this.userPhone = postData.phone;
			var postUrl = 'Login&a=modify_phone'
			if (_this.third_id) {
				postData.third_id = _this.third_id
				postData.third_from = _this.third_from
				postUrl = 'Login&a=third_id_login'
			}
			
			console.log(' 绑定手机号登录 ',postData);
			common.post(postUrl, postData, 'saveResult2', _this);
		},
		saveResult2: function(result) {
			console.log('绑定手机号登录结果', result)
			try{
				if (_this.third_id) {
					uni.$emit('loginSuccess', result)
					common.navigateBack(pageBackNum)
					return
				}
				console.log('绑定手机号登录结果111', result)
				if (result.length == 0) {
					app.globalData.userInfo.phone = _this.userPhone;
					app.globalData.userInfo.showPhone = _this.userPhone;
				} else {
					common.setUserInfo(result);
				}
			}catch(e){
				console.log(e)
			}
			console.log('绑定手机号登录结果333', pageBackNum)
			common.navigateBack(pageBackNum);
		},

		loop() {
			if (_this.config.config.international_phone) {
				if (newphone.length == 0) {
					wx.showModal({
						title: common.changeTxt('提示'),
						content: common.changeTxt('请输入手机号码'),
						showCancel: false
					});
					return false;
				}
			} else {
				if (newphone.length != 11) {
					wx.showModal({
						title: common.changeTxt('提示'),
						content: common.changeTxt('请输入11位的手机号码'),
						showCancel: false
					});
					return false;
				}
			}

			var postData = {
				phone: newphone,
				type: 3
			};

			if (_this.national_check && _this.national_check.code) {
				postData.phone_country_type = _this.national_check.code;
			}
			
			common.post('Login&a=sendCode', postData, function(result) {
				wx.hideToast();
				_this.judge = '0';
				var timer = setInterval(function() {
					if (_this.time <= 1) {
						_this.judge = 1;
						_this.time = 60;
						clearInterval(timer);
					} else {
						_this.time = _this.time - 1;
					}
				}, 1000);
			});
		},

		national_change(res) {
			this.national_check = _this.national_list[res.detail.value];
		}
	}
};
</script>
<style>
.verification {
	background: #fff;
	margin: 20rpx 0;
	border-bottom: #f1f1f1 2rpx solid;
	border-top: #f1f1f1 2rpx solid;
}

.verification .list {
	border-bottom: #f1f1f1 2rpx solid;
	padding: 24rpx 20rpx;
}

.verification .list:last-child {
	border-bottom: none;
}
.phoneInput {
	width: calc(100% - 230rpx);
	padding-top: 1rpx;
}
.codeBox {
	width: 200rpx;
	text-align: center;
}
.verification .box {
	padding: 6rpx 0rpx;
	color: #fff;
}

.verification .box button {
	margin: 0px;
	padding: 0px;
	background: #06c1ae;
	color: #fff;
	line-height: 1.5;
	font-size: 28rpx;
}

.verification .box button:after {
	border: none;
}

.verification .receive {
	background: #06c1ae;
	white-space: nowrap;
}

.verification .send_out {
	background: #ccc;
}

.button button {
	background: #06c1ae;
	color: #fff;
	margin: 0 20rpx;
	font-size: 32rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 20rpx;
}

.wxapp-button {
	margin-top: 160rpx;
	text-align: center;
}

.wxapp-button button {
	background: none;
	font-size: 28rpx;
	color: #51c332;
	border-color: #51c332;
}
.wxapp-button button image {
	width: 40rpx;
	height: 40rpx;
	vertical-align: middle;
	margin-right: 4rpx;
}

.wxapp-button.alipay .icon-zhifubao {
	margin-right: 10rpx;
	vertical-align: middle;
	font-size: 40rpx;
}

.wxapp-button.alipay button {
	color: #1cabef;
	border-color: #1cabef;
}
.user-tip{
	position: fixed;
	bottom: 0px;
	padding: 10px;
	color: #999;
	font-size: 10px;
	line-height: 1.2;
}
</style>
